import React, { useState, useEffect, useRef } from 'react';
import PropTypes from 'prop-types';

/**
 * 图片懒加载组件
 * @param {string} src - 图片真实地址
 * @param {string} alt - 图片alt文本
 * @param {string} placeholder - 占位图地址
 * @param {object} props - 其他img属性
 */
const LazyImage = ({ src, alt, placeholder, ...props }) => {
  const [isLoaded, setIsLoaded] = useState(false);
  const imgRef = useRef(null);

  useEffect(() => {
    const observer = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          const img = new Image();
          img.src = src;
          img.onload = () => {
            if (imgRef.current) {
              imgRef.current.src = src;
              setIsLoaded(true);
            }
          };
          observer.unobserve(entry.target);
        }
      });
    }, { threshold: 0.01 });

    if (imgRef.current) {
      observer.observe(imgRef.current);
    }

    return () => {
      if (imgRef.current) {
        observer.unobserve(imgRef.current);
      }
    };
  }, [src]);

  return (
    <img
      ref={imgRef}
      src={isLoaded ? src : placeholder || '/placeholder.jpg'}
      alt={alt}
      loading="lazy"
      {...props}
    />
  );
};

LazyImage.propTypes = {
  src: PropTypes.string.isRequired,
  alt: PropTypes.string.isRequired,
  placeholder: PropTypes.string,
};

/**
 * 响应式图片组件
 * @param {string} srcSet - 不同条件下的图片源
 * @param {string} sizes - 媒体查询条件
 * @param {string} src - 默认图片源
 * @param {string} alt - 图片alt文本
 * @param {object} props - 其他img属性
 */
const ResponsiveImage = ({ srcSet, sizes, src, alt, ...props }) => {
  return (
    <picture>
      <source srcSet={srcSet} sizes={sizes} type="image/webp" />
      <source srcSet={srcSet} sizes={sizes} type="image/jpeg" /> 
      <img 
        src={src} 
        alt={alt} 
        loading="lazy"
        {...props}
      />
    </picture>
  );
};

ResponsiveImage.propTypes = {
  srcSet: PropTypes.string.isRequired,
  sizes: PropTypes.string,
  src: PropTypes.string.isRequired,
  alt: PropTypes.string.isRequired,
};

/**
 * 图片优化工具函数
 */
export const imageUtils = {
  // 生成webp格式的图片URL
  getWebpUrl: (src) => {
    if (!src) return src;
    return `${src.split('.')[0]}.webp`;
  },

  // 生成不同尺寸的图片URL
  getResponsiveSrcSet: (src, sizes = [400, 768, 1024, 1440]) => {
    return sizes.map(size => `${src}?width=${size} ${size}w`).join(', ');
  }
};

export { LazyImage, ResponsiveImage };
